var express = require("express");
const { Op, QueryTypes } = require("sequelize");
var router = express.Router();

const { Dish, sequelize } = require("../models");
const { NotFoundError, success, failure } = require("../utils/response");

/**
 * 查询菜品列表
 * GET /getDishes
 */
router.post("/getByDishTypeId", async function (req, res, next) {
  try {
    // 获取查询参数 title
    const body = req.body;

    // 分页的3个参数 pageNumber pageSize offset
    const pageNumber = Math.abs(Number(body.pageNumber)) || 1;
    const pageSize = Math.abs(Number(body.pageSize)) || 10;
    const offset = (pageNumber - 1) * pageSize;
    const dishTypeId = body.dishTypeId;
    // console.log("dishTypeId", dishTypeId);

    const sql = `
SELECT 
  Dishes.id,
  Dishes.dishTypeId,
  Dishes.name,
  Dishes.description,
  Dishes.imageUrl,
  Dishes.score,
  Dishes.scoreCount,
  DishTypes.name AS dishType
FROM 
  Dishes
JOIN 
  DishTypes ON Dishes.dishTypeId = DishTypes.id
WHERE 
  Dishes.dishTypeId = ${dishTypeId}
ORDER BY 
  Dishes.createdAt DESC
LIMIT ${pageSize} OFFSET ${offset};
    `;

    const dishes = await sequelize.query(sql, {
      type: QueryTypes.SELECT,
    });

    // 查询条件
    const condition = {
      order: [["id", "ASC"]], // 排序
      limit: pageSize, // 每一页条数
      offset, // 开始位置的索引
      where: {},
    };

    // 菜品分类 dishTypeId
    if (body.dishTypeId) {
      condition.where.dishTypeId = {
        // 查询条件，模糊查询
        [Op.eq]: body.dishTypeId,
      };
    }

    // 通过模型获取数据
    const { count } = await Dish.findAndCountAll(condition);

    // 响应数据
    success(res, "查询列表成功", {
      data: dishes,
      pagination: {
        total: count,
        pageNumber,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询菜品列表
 * 根据name模糊搜索
 * GET /getDishes
 */
router.post("/getDishes", async function (req, res, next) {
  try {
    // 获取查询参数 title
    const body = req.body;

    // 分页的3个参数 pageNumber pageSize offset
    const pageNumber = Math.abs(Number(body.pageNumber)) || 1;
    const pageSize = Math.abs(Number(body.pageSize)) || 10;
    const offset = (pageNumber - 1) * pageSize;
    const name = req.body.name || "";
    const dishTypeId = body.dishTypeId;

    const sql = `
SELECT 
  Dishes.id,
  Dishes.dishTypeId,
  Dishes.name,
  Dishes.description,
  Dishes.imageUrl,
  Dishes.score,
  Dishes.scoreCount,
  DishTypes.name AS dishType
FROM 
  Dishes
JOIN 
  DishTypes ON Dishes.dishTypeId = DishTypes.id
WHERE 
  Dishes.name LIKE '%${name}%' ${
      dishTypeId ? "AND Dishes.dishTypeId = " + dishTypeId : ""
    }
ORDER BY 
  Dishes.createdAt DESC
LIMIT ${pageSize} OFFSET ${offset};
    `;

    const dishes = await sequelize.query(sql, {
      type: QueryTypes.SELECT,
    });

    // 查询条件
    const condition = {
      order: [["id", "ASC"]], // 排序
      limit: pageSize, // 每一页条数
      offset, // 开始位置的索引
      where: {},
    };

    // 如果有查询参数title则添加模糊查询
    if (body.name) {
      condition.where.name = {
        // 查询条件，模糊查询
        [Op.like]: `%${body.name}%`,
      };
    }

    // 菜品分类 dishTypeId
    if (body.dishTypeId) {
      condition.where.dishTypeId = {
        // 查询条件，模糊查询
        [Op.eq]: body.dishTypeId,
      };
    }

    // 通过模型获取数据
    const { count, rows } = await Dish.findAndCountAll(condition);

    // 响应数据
    success(res, "查询列表成功", {
      dishes,
      pagination: {
        total: count,
        pageNumber,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id查询一个菜品
 */
router.post("/getDishById", async (req, res) => {
  try {
    const { id } = req.body;
    const sql = `
SELECT 
    Dishes.id,
		Dishes.dishTypeId,
    Dishes.name,
    Dishes.description,
    Dishes.imageUrl,
    Dishes.score,
    Dishes.scoreCount,
    DishTypes.name AS dishType
FROM 
    Dishes
JOIN 
    DishTypes ON Dishes.dishTypeId = DishTypes.id
WHERE 
    Dishes.id  = ${id}`;
    const dish = await sequelize.query(sql, {
      type: QueryTypes.SELECT,
    });
    // 根据id查询
    // const dish = await Dish.findByPk(id);
    // console.log("🚀 ~ router.post ~ dish:", dish);

    if (!dish[0]) {
      return success(res, "没有查到");
    }

    success(res, "查询菜品成功", dish[0]);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建菜品
 * POST /createDish
 */
router.post("/create", async (req, res) => {
  try {
    // 白名单过滤
    const body = {
      name: req.body.name,
      dishTypeId: req.body.dishTypeId,
      description: req.body.description || "",
      imageUrl: req.body.imageUrl,
    };
    // 创建菜品
    const dish = await Dish.create(body);
    // 返回数据：状态码201
    success(res, "创建菜品成功", dish, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 修改菜品
 */
router.post("/updateDishById", async (req, res) => {
  try {
    // 菜品是否存在

    const { id } = req.body;
    console.log("id", id);
    const body = {
      name: req.body.name,
      dishTypeId: req.body.dishTypeId,
      description: req.body.description || "",
      imageUrl: req.body.imageUrl,
    };

    let dish = await Dish.findByPk(id);

    console.log("dish", dish);

    if (!dish) {
      dish = await Dish.create(body);
    }

    await dish.update(body);

    success(res, "修改成功");
  } catch (error) {
    res.status(500).json({
      status: false,
      message: "服务器错误",
      errors: [error.message],
    });
  }
});

/**
 * 根据id删除一个菜品
 */
router.post("/deleteDishById", async (req, res) => {
  try {
    // 根据id查询
    const { id } = req.body;
    const dish = await Dish.findByPk(id);

    dish?.destroy();

    success(res, "删除菜品成功");
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
